//项目管理
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  notification,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  InputNumber,
  Select,
  Spin,
} from 'antd';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';

const confirm = Modal.confirm;
const Option = Select.Option;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const Step = Steps.Step;
import moment from 'moment';
import 'moment/locale/zh-cn';


@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class houseManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      tranUnits: '',
      pageSize: 5,
      current: 1,
      tableData: [
        {
          key: '1',
          a1: '葵花小区',
          a2: '葵花楼',
          a3: '葵花大厦',
          a4: '自管',
        },
      ],
      inputValue: ['', '', '', '', null, '', '', '', '', '', null, '', '', null],
      modalVisible: false,
      province: [],
      city: [],
      area: [],
      ownerStatus: [],
      ownerType: [],
      signStatus: [],
      assetStatus: [],
      communitys: [],
      selectdIds: [],
      hookBuilds: [],
      rooms: [],
      cabinets: [],
      boxs: [],
      bags: [],

      showDownload: false,
      downloadName: '',
      downloadLink: '',
      startDownload: false,
    };
  }

  componentWillMount() {
    const that = this;

    //楼栋编码
    this.setState({
      projectCode: this.props.location.query.projectCode,
      projectName: this.props.location.query.projectName,
      communityName: this.props.location.query.communityName,
      manageType: this.props.location.query.manageType,
      transferUnit: this.props.location.query.transferUnit,
      ownershipType: this.props.location.query.ownershipType,
      buildingName2: this.props.location.query.buildingName2,
      buildingCode: this.props.location.query.buildingCode,
      obtainWay: this.props.location.query.obtainWay,
    }, () => {
      that.sendData();
    })

    //获取系统参数
    axios.all([this.getSysDic("OWNER_SHIP_STATUS"), this.getSysDic("OWNER_SHIP_TYPE"), this.getSysDic("SIGN_STATUS"), this.getSysDic("ASSET_STATUS")])
      .then(axios.spread(function (r1, r2, r3, r4) {
        that.setState({
          ownerStatus: r1.data, //权属状态
          ownerType: r2.data,  //权属形式
          signStatus: r3.data,  //签署协议状态
          assetStatus: r4.data,  //资产状态
        })
      }))


    //获取房间下拉
    this.getRoomList();
  }

  //获取房间下拉
  getRoomList = () => {
    const that = this;
    axios.post(Api.rmGetPositionList, {})
      .then(function (resp) {
        that.setState({
          rooms: resp.data
        })
      })
  }

  ///获取系统参数
  getSysDic = (type) => {
    return axios.post(Api.amGetSysDic, { key: type })
  }

  //获取表格数据
  sendData = () => {
    let that = this;
    this.setState({ loading: true })
    axios.post(Api.amGetHouseList, {
      houseName2: that.state.name,
      transferUnit: that.state.tranUnits,
      isRent: that.state.s_isRent,
      currentPage: that.state.current,
      buildingCode: that.state.buildingCode
    })
      .then(function (resp) {
        const data = resp.data;
        if (data.list.length == 0) {
          notification.destroy();
          notification['warning']({
            message: '暂无数据',
          });
        }

        data.list.forEach((d, i) => {
          d.key = i;
          //权属形式
          that.state.ownerType.forEach(item => {
            if (item.dicCode == d.ownershipType) {
              d.ownershipTypeText = item.dicName
            }
          })

          //权属状态
          that.state.ownerStatus.forEach(item => {
            if (item.dicCode == d.ownershipStatus) {
              d.ownershipStatusText = item.dicName
            }
          })
          //接收时间
          if (d.receivedDate)
            d.receivedDate = moment(d.receivedDate).format('YYYY-MM-DD HH:mm:ss')
        })

        that.setState({
          tableData: data.list,
          pageSize: data.pageSize,
          current: data.currentPage,
          total: parseInt(data.totalSize)
        })
        that.setState({ loading: false })
      })
  };

  changeIsRent = value => {
    this.setState({ s_isRent: value });
  };
  //查询
  query = () => {
    this.setState({ current: 1 }, () => {
      this.sendData();
    });
  };

  //获取项目
  getProject = id => {
    let that = this;
    //获取内容

    this.setModalVisible(true);
  };

  //编辑项目(点弹框确定)
  editProject = () => {
    let that = this;
  };

  //导出
  export = () => {
    if (this.state.selectdIds.length != 0) {
      const param = this.state.selectdIds.join(',');
      this.setState({
        startDownload: false
      });
      axios.get(Api.amExportHouse, {
        params: {
          houseCodes: param,
        },
        responseType: 'arraybuffer'
      }).then((res) => {
        notification.destroy();
        notification['success']({ message: '开始下载！' })

        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        const [dLink, name] = [
          window.URL.createObjectURL(blob),
          `房屋列表${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}.xls`
        ];
        let link = document.createElement('a');
        link.href = dLink;
        link.download = name;
        link.click();
        this.setState({
          startDownload: true,
          downloadLink: dLink,
          downloadName: name,
          showDownload: true
        });
      }).catch((err) => {
        notification.destroy();
        notification['warning']({ message: `下载失败！错误信息：${err}` })
      });
    } else {
      notification.destroy();
      notification['warning']({ message: '请选择表格中的项后进行导出！' })
    }
  };

  showDownload(showDownload) {
    this.setState({ showDownload });
  }

  changeInputValue = (e, index) => {
    let value = e.target ? e.target.value : e;
    this.setState(prevState => {
      prevState.inputValue[index] = value;
      return { inputValue: prevState.inputValue };
    });
    // console.log(e.format('YYYY-MM-DD'))
  };

  changeName = e => {
    this.setState({ name: e.target.value });
  };

  changeTranUnits = e => {
    this.setState({ tranUnits: e.target.value });
  };

  pageChange = page => {
    this.setState(
      {
        current: page,
      },
      () => {
        this.sendData();
      }
    );
  };

  setModalVisible = visible => {
    this.setState({ modalVisible: visible });
  };

  changeSelected = (selectedRowKeys, selectedRows) => {
    let selectdIds = [];
    selectedRows &&
      selectedRows.forEach((d, i, arr) => {
        selectdIds.push(d.houseCode);
      });

    this.setState({ selectedArr: selectedRowKeys, selectdIds: selectdIds });
  };

  //详情
  handleMenuClick = (item) => {
    var win = window.open(`/fe/assetMap/houseDetails?houseCode=${item.houseCode}`, '_blank');
    win.focus();
  }

  goAddPage = () => {
    router.push({
      pathname: '/fe/assetManagement/newHouse',
      state: {
        projectCode: this.state.projectCode,
        projectName: this.state.projectName,
        manageType: this.state.manageType,
        transferUnit: this.state.transferUnit,
        obtainWay: this.state.obtainWay,
        ownershipType: this.state.ownershipType,
        buildingName2: this.state.buildingName2,
        buildingCode: this.state.buildingCode,
      }
    })
  }

  goEditPage = (id) => {
    router.push({
      pathname: '/fe/assetManagement/editHouse',
      state: {
        projectCode: this.state.projectCode,
        projectName: this.state.projectName,
        manageType: this.state.manageType,
        transferUnit: this.state.transferUnit,
        obtainWay: this.state.obtainWay,
        ownershipType: this.state.ownershipType,
        houseCode: id,
        buildingName2: this.state.buildingName2,
      }
    })
  }

  deleteHouse = (id) => {
    const that = this;
    confirm({
      title: "删除确认",
      content: '确认删除该房屋？',
      onOk() {
        that.setState({ loading: true })
        axios.post(Api.amDelHouseInfo, { houseCode: id })
          .then(function (resp) {
            const { data } = resp;
            if (data.code == 1) {
              notification.destroy();
              notification['success']({ message: data.msg });
              that.sendData();
            } else {
              notification.destroy();
              notification['warning']({ message: data.msg });
            }
            that.setState({ loading: false })
          })
      }
    })
  }

  render() {

    let that = this;
    const { form: { getFieldDecorator }, currentUserLoading } = this.props;

    //表格表头
    let columns = [
      {
        title: '房屋名称',
        dataIndex: 'houseName2',
        key: 'houseName2',
        render: (text, item, index) => (
          <a href="javascrip:;" onClick={this.handleMenuClick.bind(this, item)}>
            {text}
          </a>
        ),
      },
      {
        title: '房屋编号',
        dataIndex: 'houseCode',
        key: 'houseCode',
      },
      {
        title: '建筑面积',
        dataIndex: 'buildingArea',
        key: 'buildingArea',
      },
      {
        title: '租赁状态',
        dataIndex: 'isRent',
        key: 'isRent',
      },
      {
        title: '权属形式',
        dataIndex: 'ownershipTypeText',
        key: 'ownershipTypeText',
      },
      {
        title: '用途',
        dataIndex: 'use',
        key: 'use',
      },
      {
        title: '接收日期',
        dataIndex: 'receivedDate',
        key: 'receivedDate',
      },
      {
        title: '权属状态',
        dataIndex: 'ownershipStatusText',
        key: 'ownershipStatusText',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <span>
            <a href="javascript:;" onClick={this.goEditPage.bind(this, item.houseCode)}>编辑</a>&emsp;
            <a href="javascript:;" onClick={this.deleteHouse.bind(this, item.houseCode)}>删除</a>
          </span>
        ),
      },
    ];

    if (this.props.location.state !== undefined && this.props.location.state.fromHomepage) {
      columns.unshift(
        {
          title: '项目名称',
          dataIndex: 'projectName',
          key: 'projectName',
        },
        {
          title: '楼栋名称',
          dataIndex: 'buildingName2',
          key: 'buildingName2',
        }
      );
    }

    const rowSelection = {
      selectedRowKeys: this.state.selectedArr,
      onChange: (selectedRowKeys, selectedRows) => {
        this.changeSelected(selectedRowKeys, selectedRows);
      },
    };

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>房屋管理</p>
              <p>HOUSE MANAGEMENT</p>
            </div>
          </div>

          <div className='mrb15'>
            <Form layout="inline" align='center'>
              <FormItem>
                <span className="label">房屋名称</span>
                <Input
                  value={this.state.name}
                  data-inp="zdbh"
                  onChange={this.changeName}
                  placeholder="请输入房屋名称"
                />
              </FormItem>

              <FormItem>
                <span className="label">划转单位</span>
                <Input
                  value={this.state.tranUnits}
                  data-inp="zdbh"
                  onChange={this.changeTranUnits}
                  placeholder="请输入划转单位"
                />
              </FormItem>

              <FormItem>
                <span className="label">租赁状态</span>
                <Select placeholder="请选择租赁状态" value={this.state.s_isRent} onChange={(value) => this.changeIsRent(value)}>
                  <Option value=''>&emsp;</Option>
                  <Option value='已租赁'>已租赁</Option>
                  <Option value='待租赁'>待租赁</Option>
                </Select>
              </FormItem>

              <Row gutter={24} style={{ textAlign: 'center' }}>
                <Button icon="search" type="primary" className="evfilterbtn" onClick={this.query}>
                  搜索
                  </Button>
                &emsp;
                  <Button icon="plus-circle"
                  onClick={() => this.goAddPage()}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn"
                >
                  新增房屋
                  </Button>
                &emsp;
                  <Button icon='profile' ghost
                  onClick={this.export}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn"
                >
                  生成报表
                  </Button>
              </Row>
            </Form>
          </div>


          <Spin spinning={this.state.loading}>
            <Row>
              <Table
                bordered={true}
                scroll={{ x: true }}
                align={'center'}
                columns={columns}
                dataSource={this.state.tableData}
                rowSelection={rowSelection}
                pagination={{
                  defaultPageSize: that.state.pageSize,
                  current: that.state.current,
                  onChange: that.pageChange,
                  total: that.state.total,
                  showTotal: total => `共 ${total} 项`
                }}
              />
            </Row>

            <Modal
              title="开始下载"
              visible={this.state.showDownload}
              width={400}
              wrapClassName="vertical-center-modal"
              onOk={this.showDownload.bind(this, false, 'ok')}
              onCancel={this.showDownload.bind(this, false, 'cancel')}
              style={{
                textAlign: 'center'
              }}
            >
              {this.state.downloadName !== '' ?
                <div>
                  <p>开始自动下载...</p>
                  <p><a download={this.state.downloadName} href={this.state.downloadLink}>下载没有开始，点击此链接手动下载。</a></p>
                </div>
                :
                <div>
                  <p>文件生成中，请稍后。</p>
                  <p><Icon type="loading" /></p>
                </div>
              }
            </Modal>

          </Spin>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const WrappedApp = Form.create()(houseManagement);
export default WrappedApp;
